using Microsoft.Web.WebView2.WinForms;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinApp.Models;
using WinApp.Services;

namespace WinApp.Pages
{
    public partial class PageClickActions : UIPage
    {
        private ActionClick _selectedAction = null;
        private Point _lastMousePosition;
        private WebView2 _webView2;

        public int X
        {
            get => int.TryParse(txtX.Text, out int x) ? x : 0;
            set => txtX.Text = value.ToString();
        }

        public int Y
        {
            get => int.TryParse(txtY.Text, out int y) ? y : 0;
            set => txtY.Text = value.ToString();
        }

        public PageClickActions(WebView2 webView2 = null)
        {
            _webView2 = webView2;
            InitializeComponent();
            dgvActions.AutoGenerateColumns = false;

            LoadData();
        }

        private async void btnTest_Click(object sender, EventArgs e)
        {
            ActionClick action = _selectedAction;
            if (!int.TryParse(txtX.Text, out int x))
            {
                this.ShowWarningTip("X坐标必须是整数");
                return;
            }

            if (!int.TryParse(txtY.Text, out int y))
            {
                this.ShowWarningTip("Y坐标必须是整数");
                return;
            }

            if (!int.TryParse(txtScroll.Text, out int scroll))
            {
                this.ShowWarningTip("滚动坐标必须是整数");
                return;
            }
            string text = string.Empty;
            if (!txtText.Text.IsNullOrEmpty())
                text = txtText.Text.Trim();
            action = new ActionClick
            {
                Name = txtName.Text,
                X = x,
                Y = y,
                Scroll = scroll,
                Text = text
            };
            try
            {                
                // 保存当前鼠标位置
                _lastMousePosition = Cursor.Position;

                action.WebView = _webView2;
                action.Completed += (s, e) =>
                {
                    this.ShowSuccessTip(e.Descprition);
                    Cursor.Position = _lastMousePosition;
                };

                await action.ExecuteAsync();

                // 将鼠标移回原位置
                // Thread.Sleep(100); // 稍微延迟以确保点击动作完成
                // Cursor.Position = _lastMousePosition;
            }
            catch (Exception ex)
            {
                this.ShowErrorTip($"测试点击失败: {ex.Message}");
            }
        }

        private void LoadData()
        {
            var actions = DataHelper.GetActionClicks();
            dgvActions.DataSource = null;
            dgvActions.DataSource = actions;
        }

        private void ClearInputs()
        {
            txtName.Text = "";
            txtX.Text = "0";
            txtY.Text = "0";
            txtScroll.Text = "0";
            txtText.Text = string.Empty;
            _selectedAction = null;
            dgvActions.ClearSelection();
            titlePanel1.Text = "新增点击动作";
            ValidateSaveButton();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            ClearInputs();
        }

        private void dgvActions_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvActions.SelectedRows.Count > 0)
            {
                _selectedAction = dgvActions.SelectedRows[0].DataBoundItem as ActionClick;
                if (_selectedAction != null)
                {
                    txtName.Text = _selectedAction.Name;
                    txtX.Text = _selectedAction.X.ToString();
                    txtY.Text = _selectedAction.Y.ToString();
                    txtScroll.Text = _selectedAction.Scroll.ToString();
                    txtText.Text = _selectedAction.Text;
                    titlePanel1.Text = "修改点击动作";
                }
            }
            ValidateSaveButton();
        }

        private void ValidateSaveButton()
        {
            if (string.IsNullOrWhiteSpace(txtName.Text))
            {
                btnSave.Enabled = false;
                return;
            }

            var actions = DataHelper.GetActionClicks();
            if (_selectedAction == null) // 新增模式
            {
                btnSave.Enabled = !actions.Any(a => a.Name == txtName.Text);
            }
            else // 编辑模式
            {
                btnSave.Enabled = !actions.Any(a => a.Id != _selectedAction.Id && a.Name == txtName.Text);
            }
        }

        private void txtName_TextChanged(object sender, EventArgs e)
        {
            ValidateSaveButton();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!int.TryParse(txtX.Text, out int x))
            {
                this.ShowWarningTip("X坐标必须是整数");
                return;
            }

            if (!int.TryParse(txtY.Text, out int y))
            {
                this.ShowWarningTip("Y坐标必须是整数");
                return;
            }

            if (!int.TryParse(txtScroll.Text, out int scroll))
            {
                this.ShowWarningTip("滚动坐标必须是整数");
                return;
            }

            try
            {
                if (_selectedAction == null) // 新增
                {
                    var action = new ActionClick
                    {
                        Name = txtName.Text,
                        X = x,
                        Y = y,
                        Scroll = scroll,
                        Text = txtText.Text.Trim()
                    };
                    if (DataHelper.InsertActionClick(action))
                    {
                        this.ShowSuccessTip("保存成功");
                        ClearInputs();
                        LoadData();
                    }
                }
                else // 修改
                {
                    _selectedAction.Name = txtName.Text;
                    _selectedAction.X = x;
                    _selectedAction.Y = y;
                    _selectedAction.Scroll = scroll;
                    _selectedAction.Text = txtText.Text.Trim();
                    if (DataHelper.UpdateActionClick(_selectedAction))
                    {
                        this.ShowSuccessTip("保存成功");
                        ClearInputs();
                        LoadData();
                    }
                }
            }
            catch (Exception ex)
            {
                this.ShowErrorTip(ex.Message);
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (_selectedAction == null)
            {
                this.ShowWarningTip("请先选择要删除的点击动作");
                return;
            }

            if (this.ShowAskDialog($"确定要删除点击动作 [{_selectedAction.Name}] 吗？"))
            {
                try
                {
                    if (DataHelper.DeleteActionClick(_selectedAction.Id))
                    {
                        this.ShowSuccessTip("删除成功");
                        ClearInputs();
                        LoadData();
                    }
                }
                catch (Exception ex)
                {
                    this.ShowErrorTip(ex.Message);
                }
            }
        }
    }
}
